package com.cf.base.sp.engine.impl;

import com.cf.base.sp.annotation.Level;
import com.cf.base.sp.builder.IReadBuilder;
import com.cf.base.sp.bean.SerializerInfo;
import com.cf.base.sp.engine.Converter;
import com.cf.base.sp.engine.Encryption;
import com.cf.base.sp.engine.Processor;
import com.cf.base.sp.engine.Serializer;
import com.cf.base.sp.engine.Storage;

/**
 * @author yangji
 */
public class DefaultProcessorImpl implements Processor {

    private Storage mStorage = null;
    private Converter mConverter = null;
    private Serializer mSerializer = null;
    private Encryption mEncryption = null;

    public DefaultProcessorImpl(IReadBuilder build) {
        this.mStorage = build.getStorage();
        this.mConverter = build.getConverter();
        this.mSerializer = build.getSerializer();
        this.mEncryption = build.getEncryption();
    }

    @Override
    public <T> boolean put(String key, T value, Level level) {
        //T 转String
        String content = mConverter.toString(value);

        //加密
        content = mEncryption.encrypt(key, content);

        //序列化 并存储消息类型
        content = mSerializer.serialize(value, content);

        //再次加密
        content = mEncryption.encrypt(key, content);

        //保存
        return mStorage.put(key, content, level);
    }

    @Override
    public <T> T get(String key, Level level) {
        //取出来
        String fileContent = mStorage.get(key, level);
        if (fileContent == null) {
            return null;
        }

        //解密
        String serializerContent = mEncryption.decrypt(key, fileContent);

        //反序列化
        SerializerInfo info = mSerializer.deserialize(serializerContent);
        
        //解密
        String content = mEncryption.decrypt(key, info.content);

        //根据序列化 转对象
        return mConverter.parseObject(info, content);
    }

    @Override
    public int count(Level level) {
        return mStorage.count(level);
    }

    @Override
    public boolean contains(String key, Level level) {
        return mStorage.contains(key, level);
    }

    @Override
    public void delete(String key, Level level) {
        mStorage.delete(key, level);
    }

    @Override
    public void clear(Level level) {
        mStorage.clear(level);
    }

}
